package org.monkey.common.authorization.server.controller;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.oauth2.config.SaOAuth2Config;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Handle;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Util;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import io.swagger.annotations.Api;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.monkey.common.authorization.server.entity.vo.OAuthUserInfo;
import org.monkey.common.constant.entity.Result;
import org.monkey.common.constant.exception.BaseException;
import org.monkey.request.plugin.entity.ResLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Data
@RestController
@Api(tags = "生成接口")
@Validated
public class OAuth2ServerController  {

  @Autowired
  public void setSaOAuth2Config(SaOAuth2Config cfg) {
    cfg.setNotLoginView(()->new ModelAndView("/login.html")).setDoLoginHandle((name, pwd) -> {
          if("sa".equals(name) && "123456".equals(pwd)) {
            StpUtil.login(10001);
            return SaResult.ok();
          }
          return SaResult.error("账号名或密码错误");
        }).setConfirmView((clientId, scope)->{
          Map<String, Object> map = new HashMap<>();
          map.put("clientId", clientId);
          map.put("scope", scope);
          return new ModelAndView("/confirm.html", map);
        });
  }
  @ResponseBody
  @ExceptionHandler
  public Result<String> handlerException(Exception e) {
    e.printStackTrace();
    return Result.error(new BaseException(e));
  }

  @RequestMapping("/oauth2/*")
  public Object request() {
    System.out.println("------- 进入请求: " + SaHolder.getRequest().getUrl());
    return SaOAuth2Handle.serverRequest();
  }


  @RequestMapping("/oauth2/userinfo")
  public Result<OAuthUserInfo> userinfo() {
    // 获取 Access-Token 对应的账号id
    String accessToken = SaHolder.getRequest().getParamNotNull("access_token");
    Object loginId = SaOAuth2Util.getLoginIdByAccessToken(accessToken);
    System.out.println("-------- 此Access-Token对应的账号id: " + loginId);
    // 校验 Access-Token 是否具有权限: userinfo
    SaOAuth2Util.checkScope(accessToken, "userinfo");
    // 模拟账号信息 （真实环境需要查询数据库获取信息）
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    OAuthUserInfo userInfo = new OAuthUserInfo();
    userInfo.setName( "shengzhang_");
    userInfo.setAvatar("http://xxx.com/1.jpg");
    userInfo.setAge(19);
    userInfo.setSex("1");
    userInfo.setAddress("山东省 青岛市 城阳区");
    userInfo.setMobile("13575758097");
    return Result.success(userInfo);
  }
}
